// 元素集校验器
function validator(elems) {
    var cfg;
    if (elems && elems.length > 0) {
        for (var i = 0; i < elems.length; i++) {
            // 单元分类
            cfg = elems[i];
            if (!validatorElement(cfg)) {
                return false;
            }
        }
    }
    return true;
}

function getObj(o) {
    return document.getElementById(o);
}

// 单元校验
function validatorElement(cfg) {
    if (!(cfg && cfg.id)) {
        return;
    }
    var el = getObj(cfg.id);
    // 必输项required
    // 最大值max、最小值min
    // 最大长度maxLength、最小长度minLength
    if (!(el && el.id))
        return true;
    var id, label, val, disabled, data = '';
    val = el.value;
    if (!val) {
        val = el.innerHTML;
    }
    // 必输项校验
    if (val.trim().length == 0) {
        if (cfg.required) {
            var msg = CONF.msgjoin(CONF.MsgMustInput, cfg.label, cfg.params);
            showPinLabel(el, msg);
            return false;
        }
    }

    if ('' != val) {
        var patt_code = /^[a-zA-Z0-9_\-]{1,}$/;//编号正则。。字母数字下划线^[a-zA-Z0-9_\-]{1,}$
        if ('code' == cfg.type) {
            if (!patt_code.test(val)) {
                var msg = CONF.msgjoin(CONF.MsgCode, cfg.label, []);
                el.value = "";
                showPinLabel(el, msg);
                return false;
            }
        }
    }

    if ('' != val) {
        var patt_code = /^(\d{11})|((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$/;//电话号码
        if ('phone' == cfg.type) {
            if (!patt_code.test(val)) {
                var msg = CONF.msgjoin(CONF.MsgError, cfg.label, []);
                //el.value = "";
                showPinLabel(el, msg);
                return false;
            }
        }
    }

    if ('' != val) {
        var patt_code = /^13\d{9}$|^14\d{9}$|^15\d{9}$|^18\d{9}$/;//手机号码
        if ('mobilePhone' == cfg.type) {
            if (!patt_code.test(val)) {
                var msg = CONF.msgjoin(CONF.MsgError, cfg.label, []);
                //el.value = "";
                showPinLabel(el, msg);
                return false;
            }
        }
    }


    if ('' != val) {
        var patt_code = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;//email \w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
        if ('email' == cfg.type) {
            if (!patt_code.test(val)) {
                var msg = CONF.msgjoin(CONF.MsgError, cfg.label, []);
                //el.value = "";
                showPinLabel(el, msg);
                return false;
            }
        }
    }

    if ('' != val) {
        var patt_code = /^[0-9]{6}$/;//zipcode
        if ('zipcode' == cfg.type) {
            if (!patt_code.test(val)) {
                var msg = CONF.msgjoin(CONF.MsgError, cfg.label, []);
                //el.value = "";
                showPinLabel(el, msg);
                return false;
            }
        }
    }


    /* // 检查特殊字符
     if ('' != val) {
     var patt_str = /^[^`~!@#$%^“"＂&*+=|\\\][\]\{\}:;'<>]{1}[^`~!@$%^“"&+=|\\\][\]\{\}:;'<>?]{0,33}$/;
     if (!patt_str.exec(val)) {
     var msg = CONF.msgjoin(CONF.MsgStr, cfg.label, []);
     showPinLabel(el, msg);
     return false;
     }
     }*/

    var a = stringLength(val);
    // 最大长度maxLength
    var maxL = cfg.maxlength;
    if (maxL && maxL * 1 > 0) {
        var must = cfg.mustInputAll;
        if (must && maxL > a) {
            var msg = CONF.msgjoin(CONF.MsgMustInputAll, cfg.label, [maxL]);
            showPinLabel(el, msg);
            return false;
        }
    }
    // 最小长度minLength
    var minL = cfg.minlength;

    if (minL && a < minL * 1) {
        var msg = CONF.msgjoin(CONF.MsgMinLength, cfg.label, [minL]);
        showPinLabel(el, msg);
        return false;
    }

    // 长度Length
    var Len = cfg.length;

    if (Len && a != Len * 1) {
        var msg = CONF.msgjoin(CONF.MsgLength, cfg.label, [Len]);
        showPinLabel(el, msg);
        return false;
    }

    // 验证值的类型
    // 金额类型
    var patt_money = /^(-?\d+)(\.\d+)?$/;
    if ('' != val) {
        if ('money' == cfg.type) {
            if (val < 0) {
                var msg = CONF.msgjoin(CONF.MsgMoney, cfg.label, []);
                showPinLabel(el, msg);
                return false;
            }
            if (!patt_money.test(val)) {
                var msg = CONF.msgjoin(CONF.MsgInteger, cfg.label, []);
                el.value = "";
                showPinLabel(el, msg);
                return false;
            }
        }
    }
    //int类型
    var patt_int = /^\d*$/;
    if ('' != val) {
        if ('int' == cfg.type) {
            if (!patt_int.test(val)) {
                var msg = CONF.msgjoin(CONF.MsgInteger, cfg.label, []);
                el.value = "";
                showPinLabel(el, msg);
                return false;
            }
        }
    }
    //number类型
    var patt_num = /^([-]){0,1}([0-9]){1,}([.]){0,1}([0-9]){0,}$/;
    ;
    if ('' != val) {
        if ('number' == cfg.type) {
            if (!patt_num.test(val)) {
                var msg = CONF.msgjoin(CONF.MsgInteger, cfg.label, []);
                el.value = "";
                showPinLabel(el, msg);
                return false;
            }
        }
    }

    // 最小值
    /*var minV = cfg.min;
     if (minV && minV * 1 > 0) {
     if (minV > val * 1) {
     var msg = CONF.msgjoin(CONF.MsgMinValue, cfg.label,[minV]);
     showPinLabel(el, msg);
     return false;
     }
     }*/

    // 最大值
    /*var maxV = cfg.max;
     if (maxV && maxV * 1 > 0) {
     if (maxV < val * 1) {
     var msg = CONF.msgjoin(CONF.MsgMaxValue, cfg.label,[maxV]);
     showPinLabel(el, msg);
     return false;
     }
     }*/

    // 自定义的验证方法
    if (cfg.validator) {
        try {
            return cfg.validator(el);
        } catch (e) {
        }
    }
    return true;
}
function stringLength(str) {
    return str.replace(/[^\x00-\xff]/g, "**").length;
}


function scrollto(x, y) {
    var body = document.body;
    body = body ? body : document.documentElement;
    x = x ? x : 0;
    y = y ? y : 0;
    body.scrollTop = y;
    body.scrollLeft = x;
}
function position(el) {
    pos = [el.offsetLeft, el.offsetTop];
    parent = el.offsetParent;
    if (parent != el) {
        while (parent) {
            pos[0] += parent.offsetLeft;
            pos[1] += parent.offsetTop;
            parent = parent.offsetParent;
        }
    }
    return {
        x: pos[0],
        y: pos[1]
    };
}
//显示定位标签
var _label = null;
function showPinLabel(el, msg) {
    try {
        if (el && _label && msg) {
            _label.showing = true;
            getObj("_msg").innerHTML = msg;
            var pos = position(el);
            var left = pos.x;
            var top = pos.y - 40;
            top = top < 0 ? 10 : top;
            if (el.readOnly || el.hidden) {
            } else {
                el.focus();
            }
            //posite(_label, left-30, top);
            if (_label) {
                left = left ? left : 0;
                top = top ? top : 0;
                $(_label).css("top", top);
                $(_label).css("left", left);
            }
            _label.show();
        }
    } catch (e) {
        alert(e);
    }

}

(function () {
    // Since we don't have the fallback of attachEvent and
    // other IE only stuff we won't try to run JS for IE.
    // It will run though when using Google Chrome Frame
    if (document.all) {
        return;
    }

    var currentSlideNo;
    var notesOn = false;
    var slides = document.getElementsByClassName('slide');
    var touchStartX = 0;

    var spaces = /\s+/, a1 = [""];

    var str2array = function (s) {
        if (typeof s == "string" || s instanceof String) {
            if (s.indexOf(" ") < 0) {
                a1[0] = s;
                return a1;
            } else {
                return s.split(spaces);
            }
        }
        return s;
    };

    var trim = function (str) {
        return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    };

    window.addClass = function (node, classStr) {
        classStr = str2array(classStr);
        var cls = " " + node.className + " ";
        for (var i = 0, len = classStr.length, c; i < len; ++i) {
            c = classStr[i];
            if (c && cls.indexOf(" " + c + " ") < 0) {
                cls += c + " ";
            }
        }
        node.className = trim(cls);
    };

    window.removeClass = function (node, classStr) {
        var cls;
        if (classStr !== undefined) {
            classStr = str2array(classStr);
            cls = " " + node.className + " ";
            for (var i = 0, len = classStr.length; i < len; ++i) {
                cls = cls.replace(" " + classStr[i] + " ", " ");
            }
            cls = trim(cls);
        } else {
            cls = "";
        }
        if (node.className != cls) {
            node.className = cls;
        }
    };
    window.posite = function (node, x, y) {
        if (node) {
            x = x ? x : 0;
            y = y ? y : 0;
            node.style.top = y;
            node.style.left = x;
        }
    };

})();

function getStrLength(str) {
    var strlength;
    strlength = 0;
    for (var i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) > 255) {//判断输入的是否是汉字，如果是汉字的话，则字符串长度加2
            strlength += 2;
        } else {
            strlength++;
        }
    }
    return strlength;
}

ZYConf = function () {
    _label = getObj("_label");
    _label.reverse = function () {
        if (!_label.showing) {
            $(_label).removeClass("pshow shing out flip in ");
        }
    };
    _label.hide = function () {
        $(_label).addClass('shing out');
        this.showing = false;
        setTimeout('_label.reverse()', 500);
    };
    _label.show = function () {
        $(_label).addClass("flip in pshow");
        setTimeout("_label.hide()", 2500);
    };
}

ZYConf.prototype = {
    MsgMustInput: "请输入@0@!",
    MsgMinLength: "@0@长度不小于@1@位!",
    MsgMustInputAll: "@0@必须输入@1@位!",
    MsgMinValue: "@0@不能小于@1@!",
    MsgMaxValue: "@0@不能大于@1@!",
    MsgMoney: "@0@必须大于0!",
    MsgInteger: "@0@必须是数字!",
    MsgCode: "@0@必须为字母、数字或下划线",
    MsgError: "@0@不合法",
    MsgLength: "@0@长度为@1@位!",
    MsgStr: "@0@不能包含特殊字符!",
    msgjoin: function (msg, label, params) {
        var label = label ? "'" + label + "'" : "";
        var s = msg.replace("@0@", label);
        if (params) {
            for (var i = 1; i <= params.length; i++) {
                var paraIndex = "@" + i + "@";
                s = s.replace(paraIndex, params[i - 1]);
            }
        }
        return s;
    }
}

/*下拉框
 jsonStr:json数据
 id:id的名字
 name:value的名字
 hasHead:是否带有头部
 */
function buildSelectOption(jsonStr, id, name, hasHead) {
    var sbStr = [];
    if (hasHead)
        sbStr[sbStr.length] = '<option value="">请选择</option>';
    for (var i = 0, len = jsonStr.length; i < len; i++) {
        var obj = jsonStr[i];
        if (obj["DefaultOption"] != undefined) {
            if (obj["DefaultOption"] == "1") {
                sbStr[sbStr.length] = '<option selected="selected" value="' + obj[id] + '">' + replaceHtmlTag(obj[name]) + '</option>';
            } else {
                sbStr[sbStr.length] = '<option value="' + obj[id] + '">' + replaceHtmlTag(obj[name]) + '</option>';
            }
        } else {
            sbStr[sbStr.length] = '<option value="' + obj[id] + '">' + replaceHtmlTag(obj[name]) + '</option>';
        }
    }
    return sbStr.join('');
}

//获取单据编号
/*
 1:客户编号
 2：供应商编号
 3：进货单编号
 4：销售单编号
 5：付款单编号
 6：收款单编号
 7：盘点编号
 8：商品编号
 9：存货调价编号
 10：库存流水编号
 11：资金流水编号
 12：进货退货编号
 13：销售退货编号
 14：组装拆卸编号
 15：调拨单编号
 16：借入单编号
 17：借出单编号
 18：借入归还单编号
 19：借出归还单编号
 */
function queryBillNoByType(type) {   
	
	//var billObj;
    $.ajax({
    	dataType:"json",
    	data:{
    		"SetType": type
    	},
    	url:"/Common/queryBillNoByType.json",
    	cache:false,
    	type:"post",
    	async:false,
    	success:function(data){    		
    		var IsSuccess = data.IsSuccess;    
    		return data.BillNo;
    	},
    	error:function(){
    		 Dialog.alert("error");
    	}    	
    });   
    return "";
}
/**
 * 获取当前用户名
 * @returns {*}
 */
function getUserName() {
    //var userName = parent.common_bi.getUserName("{}");
    return "test";
}

function queryBillNoByTypeObj(type, obj) {
    var billJson = {
        "SetType": type
    };
    var billObj = obj.common_bi.queryBillNoByType(JSON.stringify(billJson));
    var billJsonObj = eval("(" + billObj + ")");
    var IsSuccess = billJsonObj["IsSuccess"];
    var Message = billJsonObj["Message"];
    if (IsSuccess)
        return billJsonObj["Data"]["BillNo"];
    else
        Dialog.show(Message, obj);
}

//获取页面请求的参数
var request = {
    QueryString: function (val) {
        var uri = window.location.search;
        var re = new RegExp("" + val + "=([^&?]*)", "ig");
        return ((uri.match(re)) ? (uri.match(re)[0].substr(val.length + 1)) : null);
    }
};

/**
 * 获取页数量
 * @param count
 * @param rp
 */
function getPageCount(count, rp) {
    var pageCount = 0;
    if (count % rp == 0)
        pageCount = count / rp;
    else
        pageCount = count / rp + 1;
    return pageCount;
}

/**
 * 时间对象的格式化
 */
Date.prototype.format = function (format) {
    /*
     * format="yyyy-MM-dd hh:mm:ss";
     */
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    }

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4
            - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? o[k]
                : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}

function getNowTime() {
    var now = new Date();
    return now.format("yyyy-MM-dd");
}

function buildTime() {
    var now = new Date();
    return now.format("yyyy-MM-dd hh:mm:ss");
}


//获取系统中小数需要保留的小数位数，并返回最终结果
function getSystemDecimal(decimal) {
    var result = 0;
    if (isStringEmpty(decimal))
        result = 0;
    else
        result = Number(decimal);
    return result.toFixed(2);
}


//获取系统中小数需要保留的小数位数，并返回最终结果
function getSystemDecimalNull(decimal) {

    var result = "";
    if ("" == decimal || "None" == decimal) {
        if (typeof(decimal) == "number")
            result = Number(decimal).toFixed(2);
        else
            result = "";
    }
    else
        result = Number(decimal).toFixed(2);
    return result;
}

//判断字符串是否为空
function isStringEmpty(exp) {
    if (!exp && typeof(exp) != "undefined" && "null" != exp && "None" != exp)
        return true;
    return false;
}

function replaceNoneStr(str) {
    var resultStr = "";
    if ("None" != str && "null" != str && typeof(str) != "undefined")
        resultStr = str;
    return resultStr;

}

//替换html标签
function replaceHtmlTag(htmlStr) {
    if (!isStringEmpty(htmlStr) && htmlStr!=undefined)
        return htmlStr.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos");
    else
        return "";

}
//将字符替换成html标签
function replaceChrtoHtml(htmlStr) {
    if (!isStringEmpty(htmlStr) && htmlStr!=undefined)
        return htmlStr.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&apos/g, "'");
    else
        return "";
}

//判断数组内是否有重复值
function isRepeat(arr) {
    var hash = {};
    for (var i in arr) {
        if (hash[arr[i]])
            return true;
        hash[arr[i]] = true;
    }
    return false;
}